package view;



import dao.OrderDAO;
import dao.ProductDAO;
import dao.OrderDetailDAO;
import model.Order;
import model.OrderDetail;
import model.Product;
import model.User;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 商品列表界面类，展示商品列表并提供购买功能
 */
public class ProductListFrame extends JFrame {
    private User currentUser;          // 当前登录用户
    private ProductDAO productDAO;     // 商品数据访问对象
    private OrderDAO orderDAO;         // 订单数据访问对象
    private OrderDetailDAO orderDetailDAO; // 订单详情数据访问对象
    private JTable productTable;       // 商品表格
    private DefaultTableModel tableModel;   // 表格模型
    private JTextField quantityField;  // 数量输入框
    private JButton purchaseButton;    // 购买按钮
    private JButton backButton;        // 返回按钮

    /**
     * 构造方法，初始化商品列表界面
     * @param user 当前登录用户
     * @param productDAO 商品数据访问对象
     */
    public ProductListFrame(User user, ProductDAO productDAO) {
        currentUser = user;
        this.productDAO = productDAO;
        orderDAO = new OrderDAO();
        orderDetailDAO = new OrderDetailDAO();

        // 设置窗口标题和大小
        setTitle("在线购物系统 - 商品列表");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建面板并设置布局
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建表格模型
        tableModel = new DefaultTableModel();
        tableModel.addColumn("商品ID");
        tableModel.addColumn("商品名称");
        tableModel.addColumn("价格");
        tableModel.addColumn("类别");
        tableModel.addColumn("库存数量");

        // 创建商品表格并设置表格模型
        productTable = new JTable(tableModel);
        productTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

        // 加载商品数据到表格
        loadProducts();

        // 创建表格滚动面板
        JScrollPane scrollPane = new JScrollPane(productTable);

        // 创建输入面板并设置布局
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));

        // 创建商品选择标签
        JLabel productLabel = new JLabel("选择商品:");
        productLabel.setPreferredSize(new Dimension(100, 30));

        // 创建商品选择下拉框
        JComboBox<Integer> productComboBox = new JComboBox<>();
        List<Product> products = productDAO.getAllProducts();
        for (Product product : products) {
            productComboBox.addItem(product.getProductId());
        }
        productComboBox.setPreferredSize(new Dimension(150, 30));

        // 创建数量标签
        JLabel quantityLabel = new JLabel("数量:");
        quantityLabel.setPreferredSize(new Dimension(50, 30));

        // 创建数量输入框
        quantityField = new JTextField();
        quantityField.setPreferredSize(new Dimension(100, 30));

        // 创建购买按钮并添加事件监听器
        purchaseButton = new JButton("购买");
        purchaseButton.setPreferredSize(new Dimension(100, 30));
        purchaseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int productId = (Integer) productComboBox.getSelectedItem();
                String quantityText = quantityField.getText().trim();

                if (quantityText.isEmpty()) {
                    JOptionPane.showMessageDialog(ProductListFrame.this, "请输入购买数量！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                int quantity;
                try {
                    quantity = Integer.parseInt(quantityText);
                    if (quantity <= 0) {
                        JOptionPane.showMessageDialog(ProductListFrame.this, "购买数量必须大于 0！", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(ProductListFrame.this, "购买数量必须是正整数！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 获取选中的商品
                Product product = productDAO.getProductById(productId);
                if (product == null) {
                    JOptionPane.showMessageDialog(ProductListFrame.this, "商品不存在！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (quantity > product.getQuantity()) {
                    JOptionPane.showMessageDialog(ProductListFrame.this, "库存不足，当前库存: " + product.getQuantity(), "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 创建订单
                Order order = new Order();
                order.setUserId(currentUser.getUserId());
                order.setOrderDate(new Date());
                order.setTotalPrice(product.getPrice() * quantity);
                order.setStatus("已付款");

                orderDAO.addOrder(order);

                // 获取新添加的订单 ID
                int orderId = orderDAO.getAllOrders().get(orderDAO.getAllOrders().size() - 1).getOrderId();

                // 创建订单详情
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(orderId);
                orderDetail.setProductId(productId);
                orderDetail.setQuantity(quantity);

                orderDetailDAO.addOrderDetail(orderDetail);

                // 更新商品库存
                product.setQuantity(product.getQuantity() - quantity);
                productDAO.updateProduct(product);

                // 购买成功提示
                JOptionPane.showMessageDialog(ProductListFrame.this, "购买成功！订单号: " + orderId, "成功", JOptionPane.INFORMATION_MESSAGE);

                // 清空数量输入框
                quantityField.setText("");

                // 刷新商品列表
                loadProducts();
            }
        });

        // 创建返回按钮并添加事件监听器
        backButton = new JButton("返回");
        backButton.setPreferredSize(new Dimension(100, 30));
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 关闭商品列表界面，返回主界面
                dispose();
                new MainFrame(currentUser).setVisible(true);
            }
        });

        // 将组件添加到输入面板
        inputPanel.add(productLabel);
        inputPanel.add(productComboBox);
        inputPanel.add(quantityLabel);
        inputPanel.add(quantityField);
        inputPanel.add(purchaseButton);
        inputPanel.add(backButton);

        // 将表格滚动面板和输入面板添加到面板
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(inputPanel, BorderLayout.SOUTH);

        // 将面板添加到窗口
        add(panel);

        // 显示商品列表界面
        setVisible(true);
    }

    /**
     * 加载商品数据到表格
     */
    private void loadProducts() {
        // 清空表格
        tableModel.setRowCount(0);

        // 获取所有商品
        List<Product> products = productDAO.getAllProducts();

        // 将商品数据添加到表格
        for (Product product : products) {
            Object[] row = {
                    product.getProductId(),
                    product.getProductName(),
                    product.getPrice(),
                    product.getCategory(),
                    product.getQuantity()
            };
            tableModel.addRow(row);
        }
    }
}